//
//  Usages.swift
//  HeadlineNews
//
//  Created by han on 2019/6/14.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

// MARK: 利用泛型，搭配closure使用
@available(iOS 10.0, *)
// 不允许被继承
final class UnfairLock {
    private var unfairLock = os_unfair_lock()
    
    fileprivate func lock() {
        os_unfair_lock_lock(&unfairLock)
    }
    
    fileprivate func unlock() {
        os_unfair_lock_unlock(&unfairLock)
    }
    
    // 闭包参数返回的值就是函数返回的值，目的就是在读取参数的这段时间内加锁
    func around<T>(_ closure: () -> T) -> T {
        lock(); defer { unlock() }
        return closure()
    }
    
    func around(_ closure: () -> Void) {
        lock(); defer { unlock() }
        return closure()
    }
}

@available(iOS 10.0, *)
final class Protector<T> {
    private let lock = UnfairLock()
    private var value: T
    
    init(_ value: T) {
        self.value = value
    }
    // 创建一个线程安全的读取value的对象
    var directValue: T {
        get { return lock.around { value }}
        set { lock.around { value = newValue } }
    }
   
    // 获取到的是T,从T中获取到子元素
    func read<U>(_ closure: (T) -> U) -> U {
        return lock.around { closure(self.value) }
    }
    
    // 改变/保存的是T，或者改变T的子元素
    @discardableResult
    func write<U> (_ closure:(inout T) -> U) -> U {
        return lock.around { closure(&self.value) }
    }
}

@available(iOS 10.0, *)
class ProtectorItem {
    var item: Protector<String>
    
    init(_ item: Protector<String>) {
        self.item = item
    }
    
    func update(_ newValue: String) {
        self.item.directValue = newValue
        self.item.write { $0.append("0") }
        _ = self.item.read { $0 }
    }
}




